package com.henghai.zhenxuan.ui.page.mine;

import static com.henghai.zhenxuan.data.config.Const.KEY_ADDRESS_PARAMS;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.henghai.zhenxuan.BR;
import com.henghai.zhenxuan.data.api.UpdateConsigneeInfoApi;
import com.henghai.zhenxuan.data.bean.AddressBean;
import com.henghai.zhenxuan.data.bean.ConsigneeRepositoryBean;
import com.henghai.zhenxuan.data.repository.DataRepository;
import com.henghai.zhenxuan.domain.event.Messages;
import com.henghai.zhenxuan.domain.message.PageMessenger;
import com.henghai.zhenxuan.domain.request.AddressDelRequester;
import com.henghai.zhenxuan.domain.request.AddressListRequester;
import com.henghai.zhenxuan.ui.page.adapter.AddressListAdapter;
import com.blankj.utilcode.util.ToastUtils;
import com.henghai.zhenxuan.R;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kunminx.architecture.ui.page.BaseFragment;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.page.StateHolder;
import com.kunminx.architecture.ui.state.State;

import java.util.ArrayList;
import java.util.List;

public class MyAddressFragment extends BaseFragment {
    private MyAddressStates mStates;
    private AddressListAdapter mAdapter;
    private AddressListRequester mAddressRequester;
    private AddressDelRequester mAddressDelRequester;
    private int delPosition;
    private PageMessenger mMessenger;
    private static final String TAG = "MyAddressFragment";

    @Override
    protected void initViewModel() {
        mStates = getFragmentScopeViewModel(MyAddressStates.class);
        mAddressRequester = getFragmentScopeViewModel(AddressListRequester.class);
        mAddressDelRequester = getFragmentScopeViewModel(AddressDelRequester.class);
        mMessenger = getApplicationScopeViewModel(PageMessenger.class);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        WaitDialog dialog = WaitDialog.show("正在加载");
        mAddressRequester.getResult().observe(this, httpBeanDataResult -> {
            if (dialog.isShow()) {
                WaitDialog.dismiss();
            }
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            mStates.list.set(httpBeanDataResult.getResult().getData().getRows());
            for (AddressBean addressBean : mStates.list.get()) {
                Log.d(TAG, "onViewCreated: " + addressBean.toString());
            }
        });
        mAddressRequester.request(this);

        mAddressDelRequester.getResult().observe(this, httpBeanDataResult -> {
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            TipDialog.show("删除成功", WaitDialog.TYPE.SUCCESS);
            mAdapter.notifyItemRemoved(delPosition);
            mAddressRequester.request(this);
        });
        mMessenger.output(this, messages -> {
            if (messages.eventId == Messages.EVENT_REFRESH_ADDRESS) {
                //刷新地址列表
                mAddressRequester.request(this);
            }
        });
    }


    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new AddressListAdapter(getContext());
        mAdapter.setOnItemBtClickListener(new AddressListAdapter.OnItemBtClickListener() {
            @Override
            public void onItemDelClick(AddressBean taskBean, int position) {
                delPosition = position;
                mAddressDelRequester.request(getViewLifecycleOwner(), taskBean.getId() + "");
            }

            @Override
            public void onItemEditClick(AddressBean taskBean, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable(KEY_ADDRESS_PARAMS, taskBean);
                nav().navigate(com.henghai.zhenxuan.R.id.action_myAddressFragment_to_addAddressFragment, bundle);
//                AddEditingDialogFragment.newInstance(taskBean).setOnItemBtClickListener(new AddEditingDialogFragment.OnItemBtClickListener() {
//                    @Override
//                    public void onEditClick() {
//                        mAddressRequester.request(getViewLifecycleOwner());
//                    }
//
//                    @Override
//                    public void onSaveClick(AddressBean addressBean) {
//
//                    }
//                }).show(getChildFragmentManager(), AddEditingDialogFragment.class.getSimpleName());
            }

            @Override
            public void onItemDefaultClick(AddressBean taskBean, boolean isChecked) {
                DataRepository.getInstance().updateConsigneeInfo(getViewLifecycleOwner(),
                        new UpdateConsigneeInfoApi(new ConsigneeRepositoryBean(taskBean.getId(),
                                taskBean.getConsigneeName(),
                                taskBean.getConsigneePhone(),
                                taskBean.getConsigneeRegion(),
                                taskBean.getConsigneeAddress(),
                                isChecked ? "1" : "0"
                        )), dataResult -> {
                            if (!dataResult.getResponseStatus().isSuccess()) {
                                ToastUtils.showShort(dataResult.getResponseStatus().getResponseCode());
                            }
                            mAddressRequester.request(getViewLifecycleOwner());
                        });
            }
        });
        return new DataBindingConfig(R.layout.fragment_my_address, BR.vm, mStates).addBindingParam(BR.adapter, mAdapter)
                .addBindingParam(BR.click, new ClickProxy());
    }

    public class ClickProxy {
        public void add() {
            Bundle bundle = new Bundle();
            bundle.putSerializable(KEY_ADDRESS_PARAMS, null);
            nav().navigate(R.id.action_myAddressFragment_to_addAddressFragment, bundle);
//            AddEditingDialogFragment.newInstance(null).setOnItemBtClickListener(new AddEditingDialogFragment.OnItemBtClickListener() {
//                @Override
//                public void onEditClick() {
//                }
//                @Override
//                public void onSaveClick(AddressBean addressBean) {
//                    mAddressRequester.request(getViewLifecycleOwner());
//                }
//            }).show(getChildFragmentManager(), AddEditingDialogFragment.class.getSimpleName());

        }

        public void back() {
            nav().popBackStack();
        }
    }

    public static class MyAddressStates extends StateHolder {
        public final State<List<AddressBean>> list = new State<>(new ArrayList<>());
    }
}
